<template>
	<div id="module" class="container">
		<!-- <div class="search">
      <el-form ref="searchForm" :model="searchForm" inline label-width="90px">
        <el-form-item label="内链名称：" prop="title">
          <el-input v-model="searchForm.title" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search(searchForm)">查询</el-button>
          <el-button @click="reset(searchForm)">重置</el-button>
        </el-form-item>
      </el-form>
    </div> -->
		<div style="position: relative">
			<h3 class="title"><span />模型字段</h3>
			<el-button size="small" type="primary" icon="el-icon-arrow-left" class="back" @click="prev"
				>返回</el-button
			>
		</div>

		<el-button
			type="primary"
			class="add"
			size="small"
			icon="el-icon-plus"
			style="margin-bottom: 15px"
			@click="goAdd"
			>添加</el-button
		>
		<BouncedDialog
			:title="addForm.id ? '编辑' : '添加'"
			:dialog-show.sync="dialogShow"
			width="50%"
			class="field"
			style="margin-top: -5vh"
		>
			<el-form
				ref="addForm"
				size="small"
				:model="addForm"
				:rules="rules"
				inline
				class="addForm"
				label-width="100px"
			>
				<el-form-item label="表单标题" prop="form_title">
					<el-input v-model="addForm.form_title" />
				</el-form-item>
				<el-form-item label="数据表字段" prop="table_field">
					<el-input v-model="addForm.table_field" :disabled="addForm.id ? true : false" />
				</el-form-item>
				<el-form-item label="数据类型" prop="type">
					<el-select
						v-model="addForm.type"
						placeholder="请选择"
						:disabled="addForm.id ? true : false"
					>
						<el-option
							v-for="item in options"
							:key="item.label"
							:label="item.label"
							:value="item.label"
						/>
					</el-select>
				</el-form-item>
				<div v-if="addForm.type == '关联字段'">
					<el-form-item label="关联关系" prop="relation">
						<el-select v-model="settings.relation" @change="changeRelation">
							<el-option label="一对一" value="has_one" />
							<el-option label="一对多" value="has_many" />
							<el-option label="多对多" value="belongs_to_many" />
							<el-option label="多对一" value="belongs_to" />
						</el-select>
					</el-form-item>
					<el-form-item v-if="settings.relation == 'belongs_to_many'" label=" ">
						<el-alert
							style="line-height: 12px"
							title="温馨提示："
							description="1、如果关联表有重要(隐私)数据，强烈不建议设定为关联表，以免造成信息泄漏. 2、建议使用ID作为关联字段"
							type="error"
							:closable="false"
						/>
					</el-form-item>
					<el-form-item label="关联表">
						<el-select v-model="settings.table" filterable @change="changeTable">
							<el-option
								v-for="(item, index) in moduleTable"
								:key="index"
								:label="item.table"
								:value="item.table"
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="关联字段">
						<el-select v-model="settings.foreign_key">
							<el-option
								v-for="(item, index) in moduleField"
								:key="index"
								:label="
									item.column_comment
										? item.column_name + '(' + item.column_comment + ')'
										: item.column_name
								"
								:value="item.column_name"
							/>
						</el-select>
					</el-form-item>
					<el-form-item v-if="settings.relation == 'belongs_to_many'" label="被关联字段">
						<el-select v-model="settings.local_key">
							<el-option
								v-for="(item, index) in associatedField"
								:key="index"
								:label="
									item.column_comment
										? item.column_name + '(' + item.column_comment + ')'
										: item.column_name
								"
								:value="item.column_name"
							/>
						</el-select>
					</el-form-item>
				</div>
				<el-form-item label="排序" prop="order">
					<el-select v-model="addForm.order">
						<el-option label="ID" value="id" />
						<el-option
							v-for="item in orderList"
							:key="item.id"
							:label="item.form_title"
							:value="item.table_field"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select v-model="addForm.status">
						<el-option label="正常" :value="1" />
						<el-option label="禁用" :value="2" />
					</el-select>
				</el-form-item>
				<el-form-item label="字段为空" prop="is_null">
					<el-select v-model="addForm.is_null">
						<el-option label="允许" :value="1" />
						<el-option label="不允许" :value="2" />
					</el-select>
				</el-form-item>
				<el-form-item
					v-if="
						addForm.type == '单选' ||
						addForm.type == '多选' ||
						addForm.type == '列表多选' ||
						addForm.type == '列表' ||
						addForm.type == '开关'
					"
					label="扩展信息"
					prop="attach_data"
				>
					<el-input
						v-model="addForm.attach_data"
						placeholder="每个选项之间请用逗号隔开,例如：小学，初中，大学"
						type="textarea"
					/>
				</el-form-item>
				<el-form-item label="验证规则">
					<el-select v-model="addForm.form_validate" multiple placeholder="请选择">
						<el-option
							v-for="item in options2"
							:key="item.value"
							:label="item.label"
							:value="item.label"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="默认值" prop="default">
					<el-input v-model="addForm.default" />
				</el-form-item>
				<el-form-item label="提示信息" prop="placeholder">
					<el-input v-model="addForm.placeholder" />
				</el-form-item>
				<el-form-item label="字段长度" prop="length">
					<el-input v-model="addForm.length" />
				</el-form-item>

				<!-- <el-form-item label="附表" prop="database_table">
          <el-input v-model="addForm.database_table" />
        </el-form-item> -->
				<!-- <el-form-item label="设为系统模型">
          <el-select v-model="addForm.is_system">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="2" />
          </el-select>
        </el-form-item> -->

				<div class="btn">
					<el-button @click="dialogShow = false">取 消</el-button>
					<el-button type="primary" @click="submit()">确 定</el-button>
				</div>
			</el-form>
		</BouncedDialog>
		<el-table
			:data="orderData"
			border
			stripe
			:header-cell-style="{ 'text-align': 'center' }"
			:cell-style="{ 'text-align': 'center' }"
		>
			<el-table-column label="ID" prop="id" width="60px" />
			<el-table-column label="名称" prop="form_title" />
			<el-table-column label="字段" prop="table_field" />
			<el-table-column label="数据类型" prop="type" />
			<el-table-column label="排序" prop="order" />
			<el-table-column label="允许为空">
				<template slot-scope="scope">
					<span v-if="scope.row.is_null == 1">是</span>
					<span v-if="scope.row.is_null == 2">否</span>
				</template>
			</el-table-column>
			<el-table-column label="验证规则" prop="form_validate" />
			<el-table-column label="状态">
				<template slot-scope="scope">
					<span v-if="scope.row.status == 1">正常</span>
					<span v-else-if="scope.row.status == 2">禁用</span>
					<!-- <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="2"
            active-text="正常"
            inactive-text="禁用"
            @change="disableUser(scope.row)"
          /> -->
				</template>
			</el-table-column>
			<el-table-column label="操作" width="150px" fixed="right">
				<template slot-scope="scope">
					<!-- <el-tooltip
            v-if="scope.row.type == '关联字段'"
            effect="dark"
            class="item"
            content="关联字段，无法编辑"
            placement="top"
          >
            <el-button class="edit" size="mini">编辑</el-button>s
          </el-tooltip> -->

					<el-button class="edit" size="mini" @click="editor(scope.row)">编辑</el-button>
					<el-button class="dele" size="mini" @click="del(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- <el-pagination
      :current-page="page.currentPage"
      :page-sizes="page.pageSizes"
      :page-size="page.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
      :hide-on-single-page="page.total<page.size?true:false"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    /> -->
	</div>
</template>
<script>
import moduleApi from '@/api/module.js'
import settings from '@/settings'
export default {
	data() {
		return {
			module_id: '', // 模型id
			options: [
				{ label: '单行文本' },
				{ label: '多行文本' },
				{ label: '富文本编辑器' },
				{ label: '整数' },
				{ label: '数字' },
				{ label: '日期' },
				{ label: '时间' },
				{ label: '日期时间' },
				{ label: '日期时间区间' },
				{ label: '列表' },
				{ label: '列表多选' },
				{ label: '图片' },
				{ label: '多图' },
				{ label: '视频' },
				{ label: '多视频' },
				{ label: '文件' },
				{ label: '多文件' },
				{ label: '开关' },
				{ label: '单选' },
				{ label: '多选' },
				{ label: '关联字段' },
				{ label: '金额' },
			],
			options2: [
				{
					value: 'require',
					label: '必填',
				},
				{
					value: 'number',
					label: '整数',
				},
				{
					value: 'alpha',
					label: '字母',
				},
				{
					value: 'date',
					label: '日期',
				},
				{
					value: 'time',
					label: '时间',
				},
				{
					value: 'email',
					label: '邮箱',
				},
			],
			type: '', // 类型
			form_validate: '', // 验证规则
			orderData: [], //
			dialogShow: false,
			addForm: {
				id: '',
				form_title: '',
				table_field: '',
				type: '',
				order: '',
				status: '',
				is_null: '',
				status: '',
				form_validate: '',
				default: '',
				placeholder: '',
				length: '',
				is_system: '',
				relation: '',
				settings: {},
			},
			settings: {
				relation: 'has_one',
				table: '',
				foreign_key: '',
				local_key: '',
				table_name: '',
			},
			rules: {
				// relation: [
				//   { required: 'true', message: '请选择关联关系', trigger: 'change' }
				// ],
				form_title: [{ required: 'true', message: '请输入表单名', trigger: 'blur' }],
				table_field: [{ required: 'true', message: '请输入字段名', trigger: 'blur' }],
				order: [{ required: 'true', message: '请选择排序', trigger: 'blur' }],
				type: [{ required: 'true', message: '请选择模型类型', trigger: 'blur' }],
				status: [{ required: 'true', message: '请选择状态', trigger: 'blur' }],
				is_null: [{ required: 'true', message: '请选择是否允许字段为空', trigger: 'blur' }],
				attach_data: [{ required: 'true', message: '请输入扩展信息', trigger: 'blur' }],
			},
			searchForm: {
				title: '',
			},
			// page: {
			//   total: 0,
			//   currentPage: 1,
			//   size: 10,
			//   pageSizes: [10, 20, 30, 40]
			// }, // 分页器
			val: {},
			orderList: [],
			moduleTable: [], // 模型表
			moduleField: [], // 关联字段
			associatedField: [], // 被关联字段
			table_name: '',
		}
	},
	created() {
		this.addForm.module_id = this.$route.query.id
		this.getList()
		this.getModuleTable()
		this.getModuleInfo()
	},
	mounted() {
		// this.getTikets()
	},
	updated() {},
	methods: {
		// 模型详情
		getModuleInfo() {
			moduleApi.moduleInfo({ id: this.$route.query.id }).then((res) => {
				if (res.code == 0) {
					const database_table = res.data.database_table
					this.getAssociatedField(database_table)
				}
			})
		},
		// 获取被关联字段
		getAssociatedField(val) {
			moduleApi.moduleField({ table: val }).then((res) => {
				if (res.code == 0) {
					this.associatedField = res.data
					// if (res.data.length > 0) {
					//   this.settings.local_key = res.data[0].column_name
					// } else {
					//   this.settings.local_key = ''
					// }
				} else {
					this.$message.error(res.msg)
				}
			})
		},
		// 切换关系
		changeRelation(val) {
			if (val != 'belongs_to_many') {
				this.settings.local_key = ''
			}
		},
		// 切换关联表
		changeTable(val) {
			this.table_name = val
			this.settings.table_name = val
			this.getModuleField()
		},
		// 获取关联表
		getModuleTable() {
			moduleApi.moduleTable().then((res) => {
				if (res.code == 0) {
					this.moduleTable = res.data
					this.table_name = res.data[0].table
					this.settings.table = res.data[0].table
					this.settings.table_name = res.data[0].table
					this.getModuleField()
				} else {
					this.$message.error(res.msg)
				}
			})
		},
		// 获取关联字段
		getModuleField() {
			moduleApi.moduleField({ table: this.table_name }).then((res) => {
				if (res.code == 0) {
					this.moduleField = res.data

					if (res.data.length > 0) {
						this.settings.foreign_key = res.data[0].column_name
					} else {
						this.settings.foreign_key = ''
					}
				} else {
					this.$message.error(res.msg)
				}
			})
		},
		// 新增
		goAdd() {
			this.orderList = this.orderData
			this.addForm = {
				module_id: this.addForm.module_id,
				form_title: '',
				table_field: '',
				type: '',
				order: '',
				status: 1,
				is_null: 1,
				form_validate: '',
				default: '',
				placeholder: '',
				length: '',
				is_system: '',
			}
			this.$nextTick(() => {
				this.dialogShow = true
			})
		},
		// 编辑
		editor(row) {
			const arr = this.orderData

			this.orderList = []
			arr.forEach((el) => {
				if (el.id != row.id) {
					this.orderList.push(el)
				}
			})

			if (row.form_type == 'reference') {
				this.table_name = row.settings.table_name
				this.getModuleField()
				this.settings = row.settings
			}

			this.addForm = row
			delete this.addForm.create_time
			delete this.addForm.update_time

			this.addForm.id = row.id
			this.dialogShow = true
		},
		submit() {
			if (this.addForm.type == '关联字段') {
				this.addForm.settings = this.settings
			}

			// return
			this.$refs.addForm.validate((valid) => {
				if (valid) {
					if (!this.addForm.id) {
						moduleApi.fieldSave({ ...this.addForm }).then((res) => {
							if (res.code == 0) {
								this.$message.success(res.msg)
								this.dialogShow = false
								this.getList()
							} else {
								this.$message.error(res.msg)
							}
						})
					} else {
						moduleApi.fieldUpdate({ ...this.addForm }).then((res) => {
							if (res.code == 0) {
								this.$message.success(res.msg)
								this.dialogShow = false
								this.getList()
							} else {
								this.$message.error(res.msg)
							}
						})
					}
				} else {
					this.$message.error('请填写必要信息')
				}
			})
		},
		// 查看
		check() {},
		// 删除
		del(row) {
			this.$confirm('此操作将永久删除该模型字段, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					moduleApi.fieldDelete({ id: row.id, module_id: row.module_id }).then((res) => {
						if (res.code == 0) {
							this.$message.success(res.msg)
							this.getList()
						} else {
							this.$message.error(res.msg)
						}
					})
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除',
					})
				})
		},
		// 搜索
		search(searchForm) {
			this.$refs.searchForm.validate((valid) => {
				// this.page.currentPage = 1
				this.getList(this.val)
			})
		},
		// 重置搜索框
		reset(searchForm) {
			this.searchForm.title = ''
		},
		// 模型列表
		getList() {
			// this.val.page = this.page.currentPage
			// this.val.limit = this.page.size
			this.val.module_id = this.addForm.module_id

			// this.val.title = this.searchForm.title
			moduleApi.fieldList(this.val).then((res) => {
				this.orderData = res.data

				// this.page.total = res.count
			})
		},
		// 禁用
		disableUser(row) {
			this.addForm.status = row.status
			this.addForm.id = row.id
			this.submit()
			// moduleApi.changeStatus({ id: row.id, status: row.status }).then(res => {
			//   if (res.code == 0) {
			//     this.$message.success(res.msg)
			//     this.getList()
			//   } else {
			//     this.$message.error(res.msg)
			//   }
			// })
		},

		// // 分页规格改变
		// handleSizeChange(val) {
		//   this.page.size = val
		//   this.page.currentPage = 1
		//   this.getList()
		// },
		// // 分页点击
		// handleCurrentChange(val) {
		//   this.page.currentPage = val
		//   this.getList()
		// },
		// 返回上一页
		prev() {
			this.$router.push({ name: 'Model' })
		},
	},
}
</script>
<style lang="scss">
#module {
	.link {
		.el-select {
			width: 100%;
		}
	}
	.addForm .el-form-item__content {
		width: calc(100% - 100px);
		.el-select {
			width: 100%;
		}
	}
}
</style>
<style scoped lang="scss">
.el-table {
	margin-bottom: 20px;
}
.search {
	min-width: 1350px;
	background-color: #fff;
	padding: 35px 30px 20px;
	border-radius: 5px;
}
.el-form-item {
	width: 100%;
}
.el-dialog {
	margin-top: 5vh !important;
}
</style>
